import React, { useCallback, useEffect, useState } from 'react';
import { GUIDE_CHANGELOG, LOCAL_STORAGE_SHOW_CHANGE_LOG } from '../../../utils/constant';
import { getVersion } from '../../modules/bridge';
import { Modal } from '../UI';

const localStorageKey = LOCAL_STORAGE_SHOW_CHANGE_LOG;

export default function ShowChangeLogDialog() {
  const [visible, setVisible] = useState<boolean>(false);
  const [version, setVersion] = useState<string>('');
  const openChangeLog = useCallback(() => {
    window.open(GUIDE_CHANGELOG);
    setVisible(false);
    if (version) {
      window.localStorage.setItem(localStorageKey, version);
    }
  }, [version]);

  useEffect(() => {
    getVersion().then((rs) => {
      if (rs) {
        setVersion(rs as string);
      }
      if (rs && window.localStorage.getItem(localStorageKey) !== rs) {
        setVisible(true);
      }
    });
  }, []);

  return (
    <Modal
      title="bproxy 已升级"
      visible={visible}
      okText="查看changelog"
      cancelText="改天再看"
      onCancel={() => setVisible(false)}
      onOk={openChangeLog}
    >
      <div style={{ textAlign: 'center' }}>查看更新日志，了解 bproxy 的特性变化。</div>
    </Modal>
  );
}
